using System;
using System.Xml;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.IO;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using mshtml;
using MruMenu;

using MSHelpLib;
using MSHelpLib.BaseCode;

[assembly: AssemblyTitle("MSHelpReader.NET")]
[assembly: AssemblyDescription("MSHelpReader.NET for Windows (Desktop) - A Viewer for CHM & HXS help files with NO dependency on Microsoft products (Except .NET Framework)")]

namespace MSHelpReader
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class frmMain : System.Windows.Forms.Form
	{
		private System.Windows.Forms.StatusBar statusBar1;
		private System.Windows.Forms.StatusBarPanel statusBarPanel1;
		private System.Windows.Forms.StatusBarPanel statusBarPanel2;

		private System.Windows.Forms.ProgressBar progressBar1=null;
		private System.Windows.Forms.MainMenu mainMenu1;
		private System.Windows.Forms.MenuItem menuFile;
		private System.Windows.Forms.MenuItem menuOpen;
		private System.Windows.Forms.MenuItem menuClose;
		private System.Windows.Forms.MenuItem menuItem4;
		private System.Windows.Forms.MenuItem menuExit;
		private System.Windows.Forms.MenuItem menuRecent;
		private System.Windows.Forms.MenuItem menuItem7;
		private System.Windows.Forms.MenuItem menuHelp;
		private System.Windows.Forms.MenuItem menuAbout;
		private System.Windows.Forms.MenuItem menuHelpOnHelp;
		private System.Windows.Forms.OpenFileDialog openFileDialog1;		
		private System.Windows.Forms.TabControl tabControl1;
		private System.Windows.Forms.Splitter splitter1;
		private System.Windows.Forms.TabPage tabContents;
		private System.Windows.Forms.TabPage tabIndex;
		private System.Windows.Forms.TabPage tabSearch;
		private System.Windows.Forms.TreeView tvContents;
		private System.ComponentModel.IContainer components=null;		
		private System.Windows.Forms.ListBox lbIndex;
		private System.Windows.Forms.TextBox txtIndex;		
		private System.Windows.Forms.Button btnSearch;
		private System.Windows.Forms.TextBox txtSearch;
		private System.Windows.Forms.ListView lvSearch;
		private System.Windows.Forms.Label lbResults;
		private System.Windows.Forms.ColumnHeader colRank;
		private System.Windows.Forms.ColumnHeader colTitle;
		private System.Windows.Forms.ColumnHeader colLocation;

        private MruMenu.MruMenu mruMenu = null;				
		private MSHelpLib.IHelpSystem HelpFile=null;
		private string CHMTempDir=@"c:\temp\MSHelpView\";
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.ToolBar toolBar1;
		private System.Windows.Forms.ToolBarButton tbbBack;
		private System.Windows.Forms.ToolBarButton tbbForward;
		private System.Windows.Forms.ToolBarButton tbbNext;
		private System.Windows.Forms.ToolBarButton tbbPrevious;
		private System.Windows.Forms.MenuItem menuDecompile;
		private System.Windows.Forms.MenuItem menuItem2;
		private AxSHDocVw.AxWebBrowser Browser;
		private System.Windows.Forms.MenuItem menuItem3;
		private System.Windows.Forms.MenuItem menuFindFile;
		private FileInfo fi=null;
		private System.Windows.Forms.MenuItem menuExplore;
		private System.Windows.Forms.StatusBarPanel statusBarPanel3;
        private MenuItem menuItem5;
        private MenuItem menuItem6;
        private MenuItem menuItem8;
        private MenuItem menuItem9;
        private MenuItem menuItem10;
        private MenuItem menuItem11;
        private MenuItem menuItem12;
        private StatusBarPanel statusBarPanel4;
		private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;		

		// private bool m_bInLoop=false;

        /// <summary>
        /// Initializes a new instance of the <see cref="frmMain"/> class.
        /// </summary>
		public frmMain()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			int Width=statusBar1.Panels[0].Width;
			progressBar1=new ProgressBar();
			progressBar1.Location=new Point(0,2);
			progressBar1.Size=new Size(statusBarPanel1.Width,statusBar1.Height-2);
			progressBar1.Minimum=0;
			progressBar1.Maximum=100;			
			progressBar1.Step=1;						
			this.statusBar1.Controls.Add(progressBar1);	
	
			// Create the MRU Menu class
            mruMenu = new MruMenu.MruMenu(menuRecent, @"SOFTWARE\CHMReader\MRU");
			mruMenu.MaxEntries=10;
            mruMenu.MRUHandlerEvent += new MruMenu.MruMenu.MRUHandler(mruMenu_MRUHandlerEvent);
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain));
            this.statusBar1 = new System.Windows.Forms.StatusBar();
            this.statusBarPanel1 = new System.Windows.Forms.StatusBarPanel();
            this.statusBarPanel2 = new System.Windows.Forms.StatusBarPanel();
            this.statusBarPanel3 = new System.Windows.Forms.StatusBarPanel();
            this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);
            this.menuFile = new System.Windows.Forms.MenuItem();
            this.menuOpen = new System.Windows.Forms.MenuItem();
            this.menuClose = new System.Windows.Forms.MenuItem();
            this.menuItem4 = new System.Windows.Forms.MenuItem();
            this.menuDecompile = new System.Windows.Forms.MenuItem();
            this.menuExplore = new System.Windows.Forms.MenuItem();
            this.menuItem2 = new System.Windows.Forms.MenuItem();
            this.menuRecent = new System.Windows.Forms.MenuItem();
            this.menuItem7 = new System.Windows.Forms.MenuItem();
            this.menuExit = new System.Windows.Forms.MenuItem();
            this.menuItem3 = new System.Windows.Forms.MenuItem();
            this.menuFindFile = new System.Windows.Forms.MenuItem();
            this.menuItem5 = new System.Windows.Forms.MenuItem();
            this.menuItem6 = new System.Windows.Forms.MenuItem();
            this.menuItem8 = new System.Windows.Forms.MenuItem();
            this.menuItem9 = new System.Windows.Forms.MenuItem();
            this.menuItem10 = new System.Windows.Forms.MenuItem();
            this.menuItem11 = new System.Windows.Forms.MenuItem();
            this.menuItem12 = new System.Windows.Forms.MenuItem();
            this.menuHelp = new System.Windows.Forms.MenuItem();
            this.menuAbout = new System.Windows.Forms.MenuItem();
            this.menuHelpOnHelp = new System.Windows.Forms.MenuItem();
            this.menuItem1 = new System.Windows.Forms.MenuItem();
            this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            this.tabControl1 = new System.Windows.Forms.TabControl();
            this.tabContents = new System.Windows.Forms.TabPage();
            this.tvContents = new System.Windows.Forms.TreeView();
            this.tabIndex = new System.Windows.Forms.TabPage();
            this.txtIndex = new System.Windows.Forms.TextBox();
            this.lbIndex = new System.Windows.Forms.ListBox();
            this.tabSearch = new System.Windows.Forms.TabPage();
            this.lbResults = new System.Windows.Forms.Label();
            this.btnSearch = new System.Windows.Forms.Button();
            this.lvSearch = new System.Windows.Forms.ListView();
            this.colTitle = new System.Windows.Forms.ColumnHeader();
            this.colLocation = new System.Windows.Forms.ColumnHeader();
            this.colRank = new System.Windows.Forms.ColumnHeader();
            this.txtSearch = new System.Windows.Forms.TextBox();
            this.splitter1 = new System.Windows.Forms.Splitter();
            this.toolBar1 = new System.Windows.Forms.ToolBar();
            this.tbbBack = new System.Windows.Forms.ToolBarButton();
            this.tbbForward = new System.Windows.Forms.ToolBarButton();
            this.tbbNext = new System.Windows.Forms.ToolBarButton();
            this.tbbPrevious = new System.Windows.Forms.ToolBarButton();
            this.Browser = new AxSHDocVw.AxWebBrowser();
            this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
            this.statusBarPanel4 = new System.Windows.Forms.StatusBarPanel();
            ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel2)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel3)).BeginInit();
            this.tabControl1.SuspendLayout();
            this.tabContents.SuspendLayout();
            this.tabIndex.SuspendLayout();
            this.tabSearch.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.Browser)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel4)).BeginInit();
            this.SuspendLayout();
            // 
            // statusBar1
            // 
            this.statusBar1.Location = new System.Drawing.Point(0, 379);
            this.statusBar1.Name = "statusBar1";
            this.statusBar1.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
            this.statusBarPanel1,
            this.statusBarPanel2,
            this.statusBarPanel4,
            this.statusBarPanel3});
            this.statusBar1.ShowPanels = true;
            this.statusBar1.Size = new System.Drawing.Size(744, 22);
            this.statusBar1.TabIndex = 3;
            this.statusBar1.Text = "statusBar1";
            // 
            // statusBarPanel1
            // 
            this.statusBarPanel1.Name = "statusBarPanel1";
            this.statusBarPanel1.Width = 200;
            // 
            // statusBarPanel2
            // 
            this.statusBarPanel2.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
            this.statusBarPanel2.Name = "statusBarPanel2";
            this.statusBarPanel2.Width = 227;
            // 
            // statusBarPanel3
            // 
            this.statusBarPanel3.Name = "statusBarPanel3";
            this.statusBarPanel3.Width = 200;
            // 
            // mainMenu1
            // 
            this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuFile,
            this.menuItem3,
            this.menuHelp,
            this.menuItem1});
            // 
            // menuFile
            // 
            this.menuFile.Index = 0;
            this.menuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuOpen,
            this.menuClose,
            this.menuItem4,
            this.menuDecompile,
            this.menuExplore,
            this.menuItem2,
            this.menuRecent,
            this.menuItem7,
            this.menuExit});
            this.menuFile.Text = "&File";
            // 
            // menuOpen
            // 
            this.menuOpen.Index = 0;
            this.menuOpen.Shortcut = System.Windows.Forms.Shortcut.CtrlO;
            this.menuOpen.Text = "&Open";
            this.menuOpen.Click += new System.EventHandler(this.menuOpen_Click);
            // 
            // menuClose
            // 
            this.menuClose.Index = 1;
            this.menuClose.Text = "&Close";
            this.menuClose.Click += new System.EventHandler(this.menuClose_Click);
            // 
            // menuItem4
            // 
            this.menuItem4.Index = 2;
            this.menuItem4.Text = "-";
            // 
            // menuDecompile
            // 
            this.menuDecompile.Index = 3;
            this.menuDecompile.Text = "Decompile File";
            this.menuDecompile.Click += new System.EventHandler(this.menuDecompile_Click);
            // 
            // menuExplore
            // 
            this.menuExplore.Index = 4;
            this.menuExplore.Text = "Explore File";
            this.menuExplore.Click += new System.EventHandler(this.menuExplore_Click);
            // 
            // menuItem2
            // 
            this.menuItem2.Index = 5;
            this.menuItem2.Text = "-";
            // 
            // menuRecent
            // 
            this.menuRecent.Index = 6;
            this.menuRecent.Text = "Recent";
            // 
            // menuItem7
            // 
            this.menuItem7.Index = 7;
            this.menuItem7.Text = "-";
            // 
            // menuExit
            // 
            this.menuExit.Index = 8;
            this.menuExit.Shortcut = System.Windows.Forms.Shortcut.AltF4;
            this.menuExit.Text = "E&xit";
            this.menuExit.Click += new System.EventHandler(this.menuExit_Click);
            // 
            // menuItem3
            // 
            this.menuItem3.Index = 1;
            this.menuItem3.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuFindFile,
            this.menuItem5});
            this.menuItem3.Text = "Diag";
            // 
            // menuFindFile
            // 
            this.menuFindFile.Index = 0;
            this.menuFindFile.Text = "Find Find";
            this.menuFindFile.Click += new System.EventHandler(this.menuFindFile_Click);
            // 
            // menuItem5
            // 
            this.menuItem5.Index = 1;
            this.menuItem5.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItem6,
            this.menuItem8,
            this.menuItem9,
            this.menuItem10,
            this.menuItem11,
            this.menuItem12});
            this.menuItem5.Text = "Flags";
            // 
            // menuItem6
            // 
            this.menuItem6.Index = 0;
            this.menuItem6.Text = "Ignore Images";
            this.menuItem6.Click += new System.EventHandler(this.menuItem6_Click);
            // 
            // menuItem8
            // 
            this.menuItem8.Checked = true;
            this.menuItem8.Index = 1;
            this.menuItem8.Text = "Remove XML Tags";
            this.menuItem8.Click += new System.EventHandler(this.menuItem8_Click);
            // 
            // menuItem9
            // 
            this.menuItem9.Checked = true;
            this.menuItem9.Index = 2;
            this.menuItem9.Text = "Remove Script Tags";
            this.menuItem9.Click += new System.EventHandler(this.menuItem9_Click);
            // 
            // menuItem10
            // 
            this.menuItem10.Checked = true;
            this.menuItem10.Index = 3;
            this.menuItem10.Text = "Remove Display None";
            this.menuItem10.Click += new System.EventHandler(this.menuItem10_Click);
            // 
            // menuItem11
            // 
            this.menuItem11.Checked = true;
            this.menuItem11.Index = 4;
            this.menuItem11.Text = "Remove Size None";
            this.menuItem11.Click += new System.EventHandler(this.menuItem11_Click);
            // 
            // menuItem12
            // 
            this.menuItem12.Checked = true;
            this.menuItem12.Index = 5;
            this.menuItem12.Text = "Use HTTPDecode";
            this.menuItem12.Click += new System.EventHandler(this.menuItem12_Click);
            // 
            // menuHelp
            // 
            this.menuHelp.Index = 2;
            this.menuHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuAbout,
            this.menuHelpOnHelp});
            this.menuHelp.Text = "&Help";
            // 
            // menuAbout
            // 
            this.menuAbout.Index = 0;
            this.menuAbout.Text = "About...";
            this.menuAbout.Click += new System.EventHandler(this.menuAbout_Click);
            // 
            // menuHelpOnHelp
            // 
            this.menuHelpOnHelp.Index = 1;
            this.menuHelpOnHelp.Text = "Help";
            // 
            // menuItem1
            // 
            this.menuItem1.Index = 3;
            this.menuItem1.Text = "";
            // 
            // openFileDialog1
            // 
            this.openFileDialog1.DefaultExt = "CHM";
            this.openFileDialog1.Filter = "CHM Files (*.chm)|*.chm|MS Help 2 Files (*.hxs;*.hxi)|*.hxs;*.hxi|All Help Files|" +
                "*.chm;*.hxs;*.hxi|All Files (*.*)|*.*||";
            this.openFileDialog1.FilterIndex = 3;
            this.openFileDialog1.ShowReadOnly = true;
            this.openFileDialog1.Title = "Open Help File";
            // 
            // tabControl1
            // 
            this.tabControl1.Controls.Add(this.tabContents);
            this.tabControl1.Controls.Add(this.tabIndex);
            this.tabControl1.Controls.Add(this.tabSearch);
            this.tabControl1.Dock = System.Windows.Forms.DockStyle.Left;
            this.tabControl1.Location = new System.Drawing.Point(0, 0);
            this.tabControl1.Name = "tabControl1";
            this.tabControl1.SelectedIndex = 0;
            this.tabControl1.Size = new System.Drawing.Size(200, 379);
            this.tabControl1.TabIndex = 0;
            this.tabControl1.SelectedIndexChanged += new System.EventHandler(this.tabControl1_SelectedIndexChanged);
            // 
            // tabContents
            // 
            this.tabContents.Controls.Add(this.tvContents);
            this.tabContents.Location = new System.Drawing.Point(4, 22);
            this.tabContents.Name = "tabContents";
            this.tabContents.Size = new System.Drawing.Size(192, 353);
            this.tabContents.TabIndex = 0;
            this.tabContents.Text = "Contents";
            // 
            // tvContents
            // 
            this.tvContents.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tvContents.FullRowSelect = true;
            this.tvContents.HideSelection = false;
            this.tvContents.Location = new System.Drawing.Point(0, 0);
            this.tvContents.Name = "tvContents";
            this.tvContents.Size = new System.Drawing.Size(192, 353);
            this.tvContents.TabIndex = 0;
            this.tvContents.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvContents_AfterSelect);
            // 
            // tabIndex
            // 
            this.tabIndex.Controls.Add(this.txtIndex);
            this.tabIndex.Controls.Add(this.lbIndex);
            this.tabIndex.Location = new System.Drawing.Point(4, 22);
            this.tabIndex.Name = "tabIndex";
            this.tabIndex.Size = new System.Drawing.Size(192, 353);
            this.tabIndex.TabIndex = 1;
            this.tabIndex.Text = "Index";
            // 
            // txtIndex
            // 
            this.txtIndex.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.txtIndex.Location = new System.Drawing.Point(0, 0);
            this.txtIndex.Name = "txtIndex";
            this.txtIndex.Size = new System.Drawing.Size(192, 20);
            this.txtIndex.TabIndex = 0;
            this.txtIndex.TextChanged += new System.EventHandler(this.txtIndex_TextChanged);
            // 
            // lbIndex
            // 
            this.lbIndex.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.lbIndex.Location = new System.Drawing.Point(0, 24);
            this.lbIndex.Name = "lbIndex";
            this.lbIndex.Size = new System.Drawing.Size(192, 329);
            this.lbIndex.TabIndex = 1;
            this.lbIndex.SelectedIndexChanged += new System.EventHandler(this.lbIndex_SelectedIndexChanged);
            // 
            // tabSearch
            // 
            this.tabSearch.Controls.Add(this.lbResults);
            this.tabSearch.Controls.Add(this.btnSearch);
            this.tabSearch.Controls.Add(this.lvSearch);
            this.tabSearch.Controls.Add(this.txtSearch);
            this.tabSearch.Location = new System.Drawing.Point(4, 22);
            this.tabSearch.Name = "tabSearch";
            this.tabSearch.Size = new System.Drawing.Size(192, 353);
            this.tabSearch.TabIndex = 2;
            this.tabSearch.Text = "Search";
            // 
            // lbResults
            // 
            this.lbResults.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.lbResults.Location = new System.Drawing.Point(8, 40);
            this.lbResults.Name = "lbResults";
            this.lbResults.Size = new System.Drawing.Size(112, 16);
            this.lbResults.TabIndex = 4;
            // 
            // btnSearch
            // 
            this.btnSearch.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.btnSearch.Location = new System.Drawing.Point(128, 32);
            this.btnSearch.Name = "btnSearch";
            this.btnSearch.Size = new System.Drawing.Size(56, 23);
            this.btnSearch.TabIndex = 3;
            this.btnSearch.Text = "Search";
            this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
            // 
            // lvSearch
            // 
            this.lvSearch.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.lvSearch.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
            this.colTitle,
            this.colLocation,
            this.colRank});
            this.lvSearch.FullRowSelect = true;
            this.lvSearch.Location = new System.Drawing.Point(8, 64);
            this.lvSearch.Name = "lvSearch";
            this.lvSearch.Size = new System.Drawing.Size(176, 280);
            this.lvSearch.TabIndex = 5;
            this.lvSearch.UseCompatibleStateImageBehavior = false;
            this.lvSearch.View = System.Windows.Forms.View.Details;
            this.lvSearch.SelectedIndexChanged += new System.EventHandler(this.lvSearch_DoubleClick);
            this.lvSearch.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.lvSearch_ColumnClick);
            // 
            // colTitle
            // 
            this.colTitle.Text = "Title";
            this.colTitle.Width = 108;
            // 
            // colLocation
            // 
            this.colLocation.Text = "Location";
            // 
            // colRank
            // 
            this.colRank.Text = "Rank";
            this.colRank.Width = 40;
            // 
            // txtSearch
            // 
            this.txtSearch.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.txtSearch.Location = new System.Drawing.Point(8, 8);
            this.txtSearch.Name = "txtSearch";
            this.txtSearch.Size = new System.Drawing.Size(176, 20);
            this.txtSearch.TabIndex = 0;
            // 
            // splitter1
            // 
            this.splitter1.Location = new System.Drawing.Point(200, 0);
            this.splitter1.Name = "splitter1";
            this.splitter1.Size = new System.Drawing.Size(3, 379);
            this.splitter1.TabIndex = 5;
            this.splitter1.TabStop = false;
            // 
            // toolBar1
            // 
            this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
            this.tbbBack,
            this.tbbForward,
            this.tbbNext,
            this.tbbPrevious});
            this.toolBar1.ButtonSize = new System.Drawing.Size(90, 20);
            this.toolBar1.DropDownArrows = true;
            this.toolBar1.Location = new System.Drawing.Point(203, 0);
            this.toolBar1.Name = "toolBar1";
            this.toolBar1.ShowToolTips = true;
            this.toolBar1.Size = new System.Drawing.Size(541, 28);
            this.toolBar1.TabIndex = 7;
            this.toolBar1.TextAlign = System.Windows.Forms.ToolBarTextAlign.Right;
            this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick);
            // 
            // tbbBack
            // 
            this.tbbBack.Name = "tbbBack";
            this.tbbBack.Text = "Back";
            this.tbbBack.ToolTipText = "Navigate Back";
            // 
            // tbbForward
            // 
            this.tbbForward.Name = "tbbForward";
            this.tbbForward.Text = "Forward";
            this.tbbForward.ToolTipText = "Navigate Forward";
            // 
            // tbbNext
            // 
            this.tbbNext.Name = "tbbNext";
            this.tbbNext.Text = "Next";
            this.tbbNext.ToolTipText = "Move to next topic";
            // 
            // tbbPrevious
            // 
            this.tbbPrevious.Name = "tbbPrevious";
            this.tbbPrevious.Text = "Previous";
            this.tbbPrevious.ToolTipText = "Move to previous topic";
            // 
            // Browser
            // 
            this.Browser.Dock = System.Windows.Forms.DockStyle.Fill;
            this.Browser.Enabled = true;
            this.Browser.Location = new System.Drawing.Point(203, 28);
            this.Browser.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("Browser.OcxState")));
            this.Browser.Size = new System.Drawing.Size(541, 351);
            this.Browser.TabIndex = 8;
            this.Browser.BeforeNavigate2 += new AxSHDocVw.DWebBrowserEvents2_BeforeNavigate2EventHandler(this.Browser_BeforeNavigate2);
            this.Browser.StatusTextChange += new AxSHDocVw.DWebBrowserEvents2_StatusTextChangeEventHandler(this.Browser_StatusTextChange);
            // 
            // statusBarPanel4
            // 
            this.statusBarPanel4.Name = "statusBarPanel4";
            // 
            // frmMain
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(744, 401);
            this.Controls.Add(this.Browser);
            this.Controls.Add(this.toolBar1);
            this.Controls.Add(this.splitter1);
            this.Controls.Add(this.tabControl1);
            this.Controls.Add(this.statusBar1);
            this.Menu = this.mainMenu1;
            this.Name = "frmMain";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "MSHelpViewer.NET";
            ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel2)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel3)).EndInit();
            this.tabControl1.ResumeLayout(false);
            this.tabContents.ResumeLayout(false);
            this.tabIndex.ResumeLayout(false);
            this.tabIndex.PerformLayout();
            this.tabSearch.ResumeLayout(false);
            this.tabSearch.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.Browser)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel4)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

		}

        void Browser_StatusTextChange(object sender, AxSHDocVw.DWebBrowserEvents2_StatusTextChangeEvent e)
        {
            Trace.WriteLine(e.text);
        }

		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new frmMain());
		}

		#region frmMain General Command Handlers (Open, Close, Progress Event Handlers, Exit etc...)
		
		private void menuExit_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}

		private void menuOpen_Click(object sender, System.EventArgs e)
		{
			if (openFileDialog1.ShowDialog()==DialogResult.OK)
			{				
				OpenHelpFile(new FileInfo(openFileDialog1.FileName));
			}
		}

		private void menuClose_Click(object sender, System.EventArgs e)
		{
			if (HelpFile!=null)
			{
				tvContents.Nodes.Clear();
				lbIndex.Items.Clear();
				lvSearch.Items.Clear();
				Browser.Navigate("about:blank");
				// HelpFile.Close();
				HelpFile=null;
			}			
		}

		private void menuAbout_Click(object sender, System.EventArgs e)
		{
			frmAbout dlg=new frmAbout();
			dlg.ShowDialog();
		}

		private void mruMenu_MRUHandlerEvent(int number, string FileName)
		{
			OpenHelpFile(new FileInfo(FileName));
		}

		private void HelpFile_ProgressHandlerEvent(int Value, int MaxValue)
		{
			if (Value>progressBar1.Maximum) Value=progressBar1.Maximum;
			if (Value<progressBar1.Minimum) Value=progressBar1.Minimum;
			progressBar1.Maximum=MaxValue;
			progressBar1.Value=Value;
		}

		private void HelpFile_StatusHandlerEvent(int Level, string Info)
		{
			if (Level<0) Level=0;
			if (Level>3) Level=3;
			this.statusBar1.Panels[Level+1].Text=Info;
		}
		#endregion

		#region Open Help File
		private void OpenHelpFile(FileInfo fileInfo)
		{
			tabControl1.TabPages.Clear();

			fi=fileInfo;
			if (!File.Exists(fi.FullName))
			{
				// Remove from MRU
				mruMenu.RemoveFile(fi.FullName);

				// Save MRU List to reg.
				mruMenu.SaveToRegistry();

				// Show message box
				MessageBox.Show("Failed to find "+fi.FullName);
				return;
			}
			mruMenu.AddFile(fi.FullName);
			mruMenu.MakeFileFirst(fi.FullName);
			mruMenu.SaveToRegistry();

			// Close any previous Help Files
			if (HelpFile!=null)
				menuClose_Click(this,EventArgs.Empty);

			HelpFile=new MSHelpLib.HelpSystem();
			if (HelpFile==null)
			{
				MessageBox.Show("Failed to load help file");
				return;
			}

			HelpFile.ProgressHandlerEvent+=new ProgressHandler(HelpFile_ProgressHandlerEvent);
			HelpFile.StatusHandlerEvent+=new StatusHandler(HelpFile_StatusHandlerEvent);			

			// Open CHM File			
            // int Flags = (int)(LoadFlags.SaveDumpFile | LoadFlags.CreateSearchIndexOnFirstUseAndSave);
            int Flags = (int)(LoadFlags.SaveDumpFile | LoadFlags.CreateSearchIndexOnLoad);
            
			// HelpFile.Open(fileInfo.FullName,(int)(LoadFlags.SaveDumpFile|LoadFlags.CreateSearchIndexOnFirstUseAndSave));

            if (menuItem6.Checked) Flags += (int)LoadFlags.IgnoreImages;
            if (menuItem8.Checked) Flags += (int)LoadFlags.RemoveXMLTags;
            if (menuItem9.Checked) Flags += (int)LoadFlags.RemoveScriptTags;
            if (menuItem10.Checked) Flags += (int)LoadFlags.RemoveDisplayNone;
            if (menuItem11.Checked) Flags += (int)LoadFlags.RemoveSizeNone;
            if (menuItem12.Checked) Flags += (int)LoadFlags.HTTPDecode;

			HelpFile.Open(fileInfo.FullName,Flags);            

			progressBar1.Value=0;
			statusBarPanel2.Text="Building Contents";			

			if (HelpFile.HasTableOfContents)
			{		
				tabControl1.TabPages.Add(tabContents);
				tvContents.Nodes.Clear();	
				MSHelper.FillTree(HelpFile,tvContents);				
				tabContents.Show();
				tvContents.SelectedNode=tvContents.Nodes[0];
			}

			if (HelpFile.HasIndex)
			{
				tabControl1.TabPages.Add(tabIndex);
				MSHelper.BuildIndex(HelpFile.Index.KLinks,lbIndex);
			}

			// Handle Search Options			
			tabControl1.TabPages.Add(tabSearch);			

			statusBarPanel2.Text="Done";			
			progressBar1.Value=0;
		}
		#endregion		

		#region Contents Handler
		private void tvContents_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)		
		{				
			try
			{
				TOCItem Item=(TOCItem)e.Node.Tag;
				string Title=""; // tvContents.SelectedNode.Text;
				if (Item.Parent!=null)
				{
					TreeNode tn=Item.Parent.treeNode;
					while (tn!=null)
					{
						Title=tn.Text+"\\"+Title;
						tn=tn.Parent;
					}				
				}
				else
				{
					Title=Item.treeNode.Text;
				}

				string FileName=fi.Name.ToLower();
				FileName=FileName.Substring(0,1).ToUpper()+FileName.Substring(1);
				Title=FileName+"\\"+Title;

				if (Item.Url.EndsWith("::/"))
					return;
				
				this.statusBarPanel2.Text=Item.Url;
				DisplayPage(Item.Url,Title,true,Item.Name);
			}
			catch(Exception ex)
			{
				Trace.WriteLine(ex.Message);
			}
		}
		#endregion
		
		#region Search Handler
		/// <summary>
		///  Search Results list
		/// </summary>
		private SearchResultsTable _hits = null;

		/// <summary>
		/// Search order
		/// </summary>
		private bool ascSort = false;

		private void lvSearch_DoubleClick(object sender, System.EventArgs e)
		{
			if (lvSearch.SelectedIndices.Count!=1)
				return;
			
			SearchResultsRow row=(SearchResultsRow)_hits.DefaultView[lvSearch.SelectedIndices[0]].Row;
			string URL=row.URL;
			string Title=row.Title;
			
			string FileName=fi.Name.ToLower();
			FileName=FileName.Substring(0,1).ToUpper()+FileName.Substring(1);
			
			DisplayPage(URL,FileName+"\\"+Title);
		}

		private void btnSearch_Click(object sender, System.EventArgs e)
		{
			lvSearch.Items.Clear();			
			if (txtSearch.Text=="")
				return;		

			if (!HelpFile.CanSearch)
				return;
		
			Cursor.Current=Cursors.WaitCursor;			
			SearchResultsTable Hits=HelpFile.PerformSearch(txtSearch.Text);

			if (Hits!=null)
			{
				Hits.DefaultView.RowFilter = "";
				Hits.DefaultView.Sort="rank desc";
			}
			SetResults(Hits);			
			
			Cursor.Current=Cursors.Default;
		}

		/// <summary>
		/// Updates the search results with the records of the given datatable
		/// </summary>
		/// <param name="hits">hits table</param>
		public void SetResults(SearchResultsTable hits)
		{
			lvSearch.Items.Clear();

			_hits = hits;

			if(_hits != null)
			{
				_hits.DefaultView.RowFilter="";

				for(int i=0; i<_hits.DefaultView.Count; i++)
				{	
					SearchResultsRow row=(SearchResultsRow)_hits.DefaultView[i].Row;
					ListViewItem lvItem = new ListViewItem(row.Title);

					string Location=row.Location;
					string []parts=Location.Split('\\');
					lvItem.SubItems.Add( parts[parts.Length-1]);
					lvItem.SubItems.Add( row.Rank.ToString());
					lvSearch.Items.Add( lvItem );
				}

				lbResults.Text = _hits.DefaultView.Count.ToString() + " Result(s)";
			} 
			else 
			{
				lbResults.Text = "No results found";
			}
		}

		private void lvSearch_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
		{
			string sSort = "Title " + (ascSort ? "ASC" : "DESC");

			if(e.Column == 1)
			{
				sSort = "Location " + (ascSort ? "ASC" : "DESC");
			}
			if(e.Column == 2)
			{
				sSort = "Rank " + (ascSort ? "ASC" : "DESC");
			}

			ascSort = !ascSort;

			if(_hits != null)
			{
				_hits.DefaultView.Sort = sSort;
				SetResults(_hits);
			}		
		}	
		#endregion

		#region Index Handler
		private void txtIndex_TextChanged(object sender, System.EventArgs e)
		{
			Cursor.Current=Cursors.WaitCursor;
			MSHelper.IndexSearch(this.txtIndex.Text,lbIndex);
			Cursor.Current=Cursors.Default;
		}

		private void lbIndex_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			IndexItem2 item=(IndexItem2)lbIndex.SelectedItem;

			if (item==null)
				return;

			// Do not display if flag is true						
			if (item.bFlag==true)
				return;

			// Do not try to display Blank
			if (item.Url=="")
				return;

			// Update Status Panel
			statusBarPanel2.Text=item.Title+" : "+item.Url;
															
			string FileName="";
			if (fi!=null)
			{
				FileName=fi.Name.ToLower();
				FileName=FileName.Substring(0,1).ToUpper()+FileName.Substring(1);
			}
			
			DisplayPage(item.FullURL,FileName+"\\"+item.Title);
		}
		#endregion

		private string CheckURL(string URL)
		{
			if (URL==null)
				return null;
			if (URL=="")
				return "";

			string newURL=URL;			
			do
			{				
				if (newURL.StartsWith(@"../"))
					newURL=newURL.Substring(3);					
				else 
					break;
			}
			while(true);
			if (!newURL.StartsWith("/"))
				newURL="/"+newURL;
			return newURL;
		}


		private TOCItem FindTOCItem(string Url)
		{
			TOCItem item=(TOCItem)tvContents.Nodes[0].Tag;

			Url=CheckURL(Url);
			while (item!=null)
			{
				string LocalUrl=CheckURL(item.Local);
				if (Url.Length<=LocalUrl.Length)
				{										
					if (LocalUrl.IndexOf(Url)>=LocalUrl.Length-Url.Length)
						return item;
				}
				item=item.Next;
			}
			return null;
		}

		#region Display Page
		private void DisplayPage(string _Url, string Title)
		{
			DisplayPage(_Url, Title, false,"");
		}

        private void DisplayPage(string _Url, string Title, string ArticalName)
        {
            DisplayPage(_Url, Title, false, ArticalName);
        }

		private Stack History=new Stack(30);
		private int HistoryPointer=0;
		private void DisplayPage(string Url, string Title, bool bEnableNavButtons, string ArticalName)
		{
			if (Url=="")
				return;

            HelpPageProcessing helpPageProcessing = new HelpPageProcessing(HelpFile, Url, CHMTempDir, ArticalName);
			string helpFilePath=helpPageProcessing.Process();

			string LocalTitle="";
			if (tabControl1.TabPages.Count>0)
			{
				if (tabControl1.SelectedIndex==tabControl1.TabPages.IndexOf(tabContents))
				{
					TOCItem Item=(TOCItem)tvContents.SelectedNode.Tag;			
					if (Item!=null)
					{
						LocalTitle=tvContents.SelectedNode.Text;
					}
				}
			}
			History.Push(Url);

//			do
//			{
//				m_bInLoop=true;
			Cursor.Current=Cursors.WaitCursor;
			try
			{				
				Browser.Navigate(@"file://"+helpFilePath);
			}
			catch(Exception ex)
			{
				Trace.WriteLine(ex.Message+"\n\r"+ex.StackTrace);
			}
			Cursor.Current=Cursors.Default;

//			mshtml.IHTMLDocument2 htm = (mshtml.IHTMLDocument2) this.Browser.Document;				
//			IOleCommandTarget cmdt;
//			Object o = new object();
//			try
//			{
//				Guid cmdGuid = new Guid("ED016940-BD5B-11CF-BA4E-00C04FD70816"); // used for search dialog/inet options
//				cmdt = (IOleCommandTarget) htm;
//				// cmdt.Exec(ref cmdGuid, (uint)MiscCommandTarget.ViewSource,(uint)SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref o, ref o);
//			}
//			catch(Exception e)
//			{
//				System.Windows.Forms.MessageBox.Show(e.Message);
//			}

//				View.SetTitle(Title+LocalTitle);				
// 
//				bool bLoop=false;
//				do
//				{
//					bLoop=false;
//					
//					Cursor.Current=Cursors.Default;					
//					// Dialogs.ShowDialog(View,this);					
//					// View.Text="CHMReader.Net";
//					Cursor.Current=Cursors.WaitCursor;
//
//					TreeNode SNode=null;
//					switch(View.WhereNext)
//					{
//						case EnumWhereNext.Next : 												
//							SNode=tvContents.SelectedNode;
//							item=(TOCItem)SNode.Tag;
//							if (item!=null)
//							{
//								while((item!=null) && (item.Next!=null))
//								{
//									Url=item.Next.Url;								
//									if (!Url.EndsWith("::/"))								
//										break;
//									item=item.Next;
//								}
//								tvContents.SelectedNode=item.Next.treeNode;
//								LocalTitle=item.Next.Name;
//							}
//							break;
//
//						case EnumWhereNext.Prev : 
//							SNode=tvContents.SelectedNode;
//							item=(TOCItem)SNode.Tag;
//							if (item!=null)
//							{
//								while ((item!=null) && (item.Prev!=null))
//								{
//									Url=item.Prev.Url;
//									if (!Url.EndsWith("::/"))								
//										break;
//									item=item.Prev;
//								}
//								tvContents.SelectedNode=item.Prev.treeNode;
//								LocalTitle=item.Prev.Name;
//							}
//							break;
//
//						case EnumWhereNext.Close: 
//							bQuit=true;
//							break;
//
//						case EnumWhereNext.None : 
//							bQuit=true;
//							break;
//
//						case EnumWhereNext.Link:												
//							Url=View.Link;
//
//							// Handle Jump to anchor within local HTML File.
//							if (Url.StartsWith("#"))
//							{
//								bLoop=true;
//								View.SetAnchor(Url.Substring(1));
//								LocalTitle="";
//							}
//							else
//							{
//								bLoop=false;
//								item=FindTOCItem(Url);
//								if (item!=null)
//								{
//									tvContents.SelectedNode=item.treeNode;
//									LocalTitle=item.Name;
//								}
//							}
//							break;
//					}
//				}
//				while (bLoop==true);				
//			}
//			while(bQuit==false);
//			m_bInLoop=false;			
		}		
		#endregion

		private void Browser_BeforeNavigate2(object sender, AxSHDocVw.DWebBrowserEvents2_BeforeNavigate2Event e)
		{	
			string URL=e.uRL.ToString();
			Trace.WriteLine("Navigate to : "+URL);			

			URL=MSHelpLib.HttpUtility.UrlDecode(URL);
			if (   (URL.ToLower().IndexOf(@"::\\exec=")!=-1)
				|| (URL.ToLower().IndexOf(@"::\\#")!=-1)
				|| (URL.ToLower().IndexOf(@"::\\chm=")!=-1)
				)
			{
				// Do not allow these URL's
				URL=(string)History.Pop();
			}			

			if ((URL.ToLower().StartsWith("ms-its:")) || (URL.ToLower().StartsWith("ms-help:")))
			{
				SyncContents(URL);
				DisplayPage(URL, "Title",false,"");
			}			
		}

		private bool SyncContents(string TopicURL)
		{
			if (!HelpFile.HasTableOfContents)
				return false;

			string URL=TopicURL.ToLower();
			URL=URL.Replace(@"\\",@"\");
			URL=URL.Replace(@"\",@"/");
			TOCItem item=(TOCItem)tvContents.Nodes[0].Tag;
			do
			{
				if (item.Url!=null)
				{
					string ItemURL=item.Url.ToLower();
					ItemURL=ItemURL.Replace(@"\\",@"\");
					ItemURL=ItemURL.Replace(@"\",@"/");
					if (ItemURL==URL)
					{
						tvContents.SelectedNode=item.treeNode;
						item.treeNode.EnsureVisible();					
						return true;
					}		
				}
				item=item.Next;
			}
			while (item!=null);
			return false;
		}

		#region ToolBar Handler
		private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
		{
			try
			{
				if (e.Button==tbbBack)
				{				
					if (HistoryPointer>0)
					{
						HistoryPointer--;						
						string Url=(string)History.Pop();

						// SyncContents will select item in tree if found & display page via AfterSelect
						// else just display page
						if (!SyncContents(Url))
							DisplayPage(Url,"");
					}
				}

				if (e.Button==tbbForward)
				{
					if (HistoryPointer<History.Count)
					{
						HistoryPointer++;
						string Url=(string)History.Pop();						

						// SyncContents will select item in tree if found & display page via AfterSelect
						// else just display page
						if (!SyncContents(Url))
							DisplayPage(Url,"");
					}
				}

				TOCItem item=(TOCItem)tvContents.SelectedNode.Tag;

				if (e.Button==tbbNext)
					tvContents.SelectedNode=item.Next.treeNode;				

				if (e.Button==tbbPrevious)
					tvContents.SelectedNode=item.Prev.treeNode;
			}
			catch(Exception ex)
			{
				Trace.WriteLine(ex.Message);
			}
		}
		#endregion

		#region Decompiler
		private MSHelpLib.PAFEnum ExtractFile(IFileInfo fileInfo)
		{
			if (fileInfo.Length>0)
			{	
				statusBarPanel2.Text="Extracting "+fileInfo.FileName;
				progressBar1.PerformStep();
			
				string HelpFileName=fileInfo.FileName;
				HelpFileName=HelpFileName.Replace("$","");
				HelpFileName=HelpFileName.Replace(":","");
				HelpFileName=HelpFileName.Replace("/",@"\");
				
				MemoryStream ms=DecompileFile.Extract(fileInfo);
				FileInfo info=new FileInfo(HelpFileName);

				string NewName="";
				if ((info.Directory.Name.Length>=3) && (info.Directory.Name.Substring(1,2)==@":\"))
					NewName=m_ExtractDir+@"\"+info.Name;
				else					
					NewName=m_ExtractDir+@"\"+info.Directory.Name+@"\"+info.Name;
				
				FileInfo info2=new FileInfo(NewName);				
				Directory.CreateDirectory(info2.DirectoryName);

				FileStream fs=new FileStream(NewName,FileMode.Create,FileAccess.Write,FileShare.None);
				byte [] buf= ms.ToArray();
				fs.Write(buf,0,buf.Length);
				fs.Close();
			}
			return MSHelpLib.PAFEnum.Continue;
		}

		private string m_ExtractDir="";
		private MSHelpLib.IHelpSystem DecompileFile=null;
		private void menuDecompile_Click(object sender, System.EventArgs e)
		{
			if (openFileDialog1.ShowDialog()!=DialogResult.OK)
				return;
			string FileName=openFileDialog1.FileName;

			FolderBrowserDialog FolderDlg=new FolderBrowserDialog();
			if (FolderDlg.ShowDialog()!=DialogResult.OK)
				return;

			m_ExtractDir=FolderDlg.SelectedPath;
			Directory.CreateDirectory(m_ExtractDir);

			FileInfo fi=new FileInfo(FileName);
			DecompileFile=null;

			DecompileFile=new MSHelpLib.HelpSystem();					
			progressBar1.Minimum=0;
			progressBar1.Maximum=200;
			progressBar1.Value=0;
			progressBar1.Step=1;
			DecompileFile.Open(FileName,(int)(LoadFlags.LoadOnlySystemData|LoadFlags.RemoveScriptTags));
			DecompileFile.ProcessAllFiles(new MSHelpLib.ProcessAllFilesDelegate(ExtractFile));			
			statusBarPanel2.Text="";
			progressBar1.Value=0;
		}
		#endregion

		#region FindFind
		private ArrayList Results=null;
		private string FileToFile="";
		private System.Text.RegularExpressions.Regex reFindFile=null;
		private MSHelpLib.PAFEnum CheckFiles(IFileInfo fileInfo)
		{
			if (fileInfo.Length>0)
			{	
				string HelpFileName=fileInfo.FileName.ToLower();
				if (reFindFile.IsMatch(HelpFileName))
				{					
					Results.Add(fileInfo.FileName+":"+fileInfo.HelpStream.FileName);
				}				
			}
			return MSHelpLib.PAFEnum.Continue;
		}
		
		private void menuFindFile_Click(object sender, System.EventArgs e)
		{
			// Ask for Drive/Directory to search
			if (folderBrowserDialog1.ShowDialog()!=DialogResult.OK)
				return;
			string SelectedPath=folderBrowserDialog1.SelectedPath;

			// Ask for file to search for.
			FindFileIn dlg=new FindFileIn();
			if (dlg.ShowDialog()!=DialogResult.OK)
				return;
			FileToFile=dlg.txtFileName.Text;

			reFindFile=new Regex(dlg.txtFileName.Text,RegexOptions.Singleline|RegexOptions.IgnorePatternWhitespace|RegexOptions.IgnoreCase);

			DirectoryInfo di=new DirectoryInfo(SelectedPath);
			Results=new ArrayList();
			progressBar1.Value=0;
			progressBar1.Step=1;

			FileInfo [] FilesCHM=di.GetFiles("*.ch*");
			FileInfo [] FilesHXS=di.GetFiles("*.hx*");
			ArrayList files=new ArrayList();

			foreach(FileInfo f in FilesHXS)
				files.Add(f);
			foreach(FileInfo f in FilesCHM)
				files.Add(f);			
			
			Results=new ArrayList();
			progressBar1.Minimum=0;
			progressBar1.Maximum=FilesCHM.GetLength(0)+FilesHXS.GetLength(0);
			foreach(FileInfo fi in files)
			{			
				progressBar1.PerformStep();
				statusBarPanel2.Text="Loading "+fi.Name;
				DecompileFile=null;
				DecompileFile=new MSHelpLib.HelpSystem();						
				DecompileFile.Open(fi.FullName);				
				statusBarPanel2.Text="Checking files in "+fi.Name;
				DecompileFile.ProcessAllFiles(new MSHelpLib.ProcessAllFilesDelegate(CheckFiles));
			}	
			progressBar1.Value=0;
			statusBarPanel2.Text="All Done";

			if (Results.Count==0)
				MessageBox.Show("No Results Found");
			else
			{
				string text="<B>Results</B><br>";
				foreach(string s in Results)
				{
					text+=s+"<br>";
				}

				string ResultsFileName=this.CHMTempDir+@"Results.htm";
				StreamWriter sw=new StreamWriter(ResultsFileName);
				sw.WriteLine(text);
				sw.Close();
				this.Browser.Navigate(ResultsFileName);
			}
		}
		#endregion
				
		#region Explore File
		private void menuExplore_Click(object sender, System.EventArgs e)
		{
			if (openFileDialog1.ShowDialog()!=DialogResult.OK)
				return;

			frmExplorer dlg=new frmExplorer(openFileDialog1.FileName);
			dlg.ShowDialog();			
		}
		#endregion
				
		private void tabControl1_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (tabControl1.SelectedTab==this.tabSearch)
			{
				if (HelpFile!=null)
				{					
					HelpFile.InitSearch();
				}
			}
		}

        private void menuItem6_Click(object sender, EventArgs e)
        {
            menuItem6.Checked = !menuItem6.Checked;
            UpdateFlags(menuItem12.Checked, LoadFlags.IgnoreImages);
        }

        private void menuItem8_Click(object sender, EventArgs e)
        {
            menuItem8.Checked = !menuItem8.Checked;
            UpdateFlags(menuItem12.Checked, LoadFlags.RemoveXMLTags);
        }

        private void menuItem9_Click(object sender, EventArgs e)
        {
            menuItem9.Checked = !menuItem9.Checked;
            UpdateFlags(menuItem12.Checked, LoadFlags.RemoveScriptTags);
        }

        private void menuItem10_Click(object sender, EventArgs e)
        {
            menuItem10.Checked = !menuItem10.Checked;
            UpdateFlags(menuItem12.Checked, LoadFlags.RemoveDisplayNone);
        }

        private void menuItem11_Click(object sender, EventArgs e)
        {
            menuItem11.Checked = !menuItem11.Checked;
            UpdateFlags(menuItem12.Checked, LoadFlags.RemoveSizeNone);
        }

        private void menuItem12_Click(object sender, EventArgs e)
        {
            menuItem12.Checked = !menuItem12.Checked;
            UpdateFlags(menuItem12.Checked, LoadFlags.HTTPDecode);
        }

        private void UpdateFlags(bool bSet, LoadFlags flag)
        {
            if (HelpFile == null)
                return;
            if (bSet)
                HelpFile.Flags |= (int)flag;
            else
                HelpFile.Flags &= int.MaxValue-(int)flag;
        }
	}

	#region Internal Data Classes
	internal class UrlString
	{
		public string URLString="";
		public long Offset=0;
		public UrlString(string _Url, long _Offset)
		{
			URLString=_Url;
			Offset=_Offset;
		}
	}

	internal class HXTopic
	{
		public long Word1=0;
		public long Word2=0;
		public HXTopic(long _Word1, long _Word2)
		{
			Word1=_Word1;
			Word2=_Word2;
		}

		public void Dump(Hashtable StringsHash, Hashtable URLStringsHash)
		{
			Trace.WriteLine(StringsHash[Word1.ToString()]+" = "+URLStringsHash[Word2.ToString()]);
		}
	}
	#endregion

	#region For find/inet options
	[StructLayout(LayoutKind.Sequential)]
	internal struct OLECMDTEXT
	{
		public uint cmdtextf;
		public uint cwActual;
		public uint cwBuf;
		[MarshalAs(UnmanagedType.ByValTStr,SizeConst=100)]public char rgwz;
	}

	[StructLayout(LayoutKind.Sequential)]
	internal struct OLECMD
	{
		public uint cmdID;
		public uint cmdf;
	}

	// Interop definition for IOleCommandTarget.
	[ComImport]
	[Guid("b722bccb-4e68-101b-a2bc-00aa00404770")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	internal interface IOleCommandTarget
	{
		//IMPORTANT: The order of the methods is critical here. You
		//perform early binding in most cases, so the order of the methods
		//here MUST match the order of their vtable layout (which is determined
		//by their layout in IDL). The interop calls key off the vtable ordering,
		//not the symbolic names. Therefore, if you switched these method declarations
		//and tried to call the Exec method on an IOleCommandTarget interface from your
		//application, it would translate into a call to the QueryStatus method instead.
		void QueryStatus(ref Guid pguidCmdGroup, UInt32 cCmds,
			[MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] OLECMD[] prgCmds, ref OLECMDTEXT CmdText);
		void Exec(ref Guid pguidCmdGroup, uint nCmdId, uint nCmdExecOpt, ref object pvaIn, ref object pvaOut);
	}

	internal enum MiscCommandTarget
	{
		Find = 1,
		ViewSource,
		Options
	}
	#endregion
}
